package com.czy.owner.ui.workorder;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.api.OrderCouponApi;
import com.czy.owner.api.PaymentCancleApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.OrderCouponsListModel;
import com.czy.owner.entity.PickCardEntity;
import com.czy.owner.entity.PrePayBalancePaymentModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.order.PicCouponActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.widget.MoneyEditText;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hep on 2017/9/7.
 * 支付尾款
 */
public class PaidEndOfPaymentActivity2 extends BaseActivity {
    @BindView(R.id.tv_use_yue_error)
    TextView tvUseYueError;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.relative_discount_coupon)
    RelativeLayout relativeDiscountCoupon;
    @BindView(R.id.img_right_coupon)
    ImageView imgRightCoupon;
    //    @BindView(R.id.tv_all_jine)
//    TextView ;//总金额
    private String tvAllJine;
    //    @BindView(R.id.tv_had_paid_dingjin)
//    TextView tvHadPaidDingJin;//已支付tv_money_title
    @BindView(R.id.tv_money_title)
    TextView tvMoneyTitle;//
    @BindView(R.id.tv_actual_payment)
    TextView tvActualPayment;//
    @BindView(R.id.tv_end_of_payment)
    TextView tvEndOfPayment;//尾款金额
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;//优惠券
    @BindView(R.id.tv_project_card)
    TextView tvProjectCard;//项目卡
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//使用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;//第三方支付还需多少
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox
    //三方支付
    @BindView(R.id.linear_three_payment)
    LinearLayout linearThreePayment;

    @BindView(R.id.relat_select_payment)
    RelativeLayout relatSelectPayment;

    @BindView(R.id.et_service_despost_price)
    MoneyEditText etServiceDespostPrice;
    //挂账
    @BindView(R.id.relat_bill)
    RelativeLayout relatBill;
    //余额支付
    @BindView(R.id.relat_balance)
    RelativeLayout relatBalance;
    private int storeId = 0;
    private String orderNumber, userOrderId;
    private static final int SDK_PAY_FLAG = 1;//支付
    private String selectedPaidType = "aliPay";
    //    private String useStoreBalance = "false";
    private boolean isUseStoreBalance = false;
    //余额支付
    private double storeBalance;

    private double realityPaid; //实际支付
    //余款
    private double balanceMoney;
    private double couponMoney;//优惠券金额
    private boolean isAllBillAmount;//是否全部挂账支付
    private double billAmount; //挂账金额
    private MyInputPwdUtil myInputPwdUtil;

    private PrePayBalancePaymentModel paymentData = null;

    private static final int COUPONS_LIST = 1111;//券列表
    private static final int CARDS_LIST = 0X12;//卡列表

    private boolean isbespoke;
    private List<OrderCouponsListModel> couponsList = new ArrayList<>();//优惠券集合
    private OrderCouponsListModel orderCouponsListModel;
    private int isPosition = -1;
    private boolean isMessage;
    //是否允许挂账
    private boolean isAllowBill;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        updataUserInfo();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity2.this, "支付取消");
                        getPaymentCancle();
                    } else {
                        getPaymentCancle();
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity2.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_paid_endof_payment2;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        isMessage = getIntent().getBooleanExtra("isMessage", false);
        orderNumber = getIntent().getStringExtra("orderNumber");
        userOrderId = getIntent().getStringExtra("userOrderId");
        isbespoke = getIntent().getBooleanExtra("isbespoke", true);

        toolbarTitle.setText("支付");
        if (isbespoke) {
//            getToolbarTitle().setText(R.string.paid_end_of_payment);
            tvMoneyTitle.setText("待付尾款");
        } else {
//            getToolbarTitle().setText("待付金额");
            tvMoneyTitle.setText("待付金额");
        }

        storeId = getIntent().getIntExtra("storeId", 0);
        //挂账输入框，每次变化界面变动
        etServiceDespostPrice.setOnEtitClickLinear(new MoneyEditText.OnEtitClickLinear() {
            @Override
            public void editClick(String text) {
                billAmount = Double.parseDouble(text);
                if (Double.parseDouble(text) >= DecimalUtil.formatDoubleNum(balanceMoney - couponMoney)) {
                    isAllBillAmount = true;
                    relatBalance.setVisibility(View.GONE);
                    linearThreePayment.setVisibility(View.GONE);
                    tvSdkPaidTip.setVisibility(View.GONE);

                } else {
                    isAllBillAmount = false;
                    relatBalance.setVisibility(View.VISIBLE);
                    linearThreePayment.setVisibility(View.VISIBLE);
                    realityPaid = DecimalUtil.formatDoubleNum(balanceMoney - (storeBalance + couponMoney + billAmount));
                    MyLog.e("hep", realityPaid + "----");
                    if (realityPaid > 0) {
                        isUseStoreBalance = false;
                        tvUseYueError.setVisibility(View.VISIBLE);
                    } else {

                        isUseStoreBalance = true;
                        tvUseYueError.setVisibility(View.GONE);
                    }
                    setPaymentText();
                }
                tvActualPayment.setText("(实际支付¥" + DecimalUtil.formatNum(balanceMoney - (couponMoney + billAmount) + "") + ")");
                setPaymentNum();
            }
        });
        userPayInfoData();
        getCoupons();
        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(PaidEndOfPaymentActivity2.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
    }

    public void setPaymentText() {
        if (cbYue.isChecked()) {
            if (isUseStoreBalance) {
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
            }
            cbYuEOnClick(cbYue);
        }

    }

    //设置富文本不同颜色
    public void setPaymentNum() {
//        tvActualPayment.setText("(实际支付¥" + (balanceMoney - (couponMoney + billAmount)) + ")");
        if (balanceMoney - (couponMoney + billAmount) == 0) {
            relatSelectPayment.setVisibility(View.GONE);
        } else {
            relatSelectPayment.setVisibility(View.VISIBLE);
        }
        SpannableString spannableString = new SpannableString(tvActualPayment.getText().toString());
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#07a7ad")), tvActualPayment.getText().toString().indexOf("¥"), spannableString.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvActualPayment.setText(spannableString);
    }

    @Override
    protected void updateViews() {

    }

    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PaidEndOfPaymentActivity2.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(PaidEndOfPaymentActivity2.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");
                if (flag) {
                    myInputPwdUtil.hide();
                    payEndOfPayMent();
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidEndOfPaymentActivity2.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(PaidEndOfPaymentActivity2.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidEndOfPaymentActivity2.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(PaidEndOfPaymentActivity2.this, exp);
                            break;
                        default:
                            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity2.this, "服务器连接失败");
                            break;
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    //获取优惠券
    private void getCoupons() {
        OrderCouponApi orderCouponApi = new OrderCouponApi(new HttpOnNextListener<List<OrderCouponsListModel>>() {
            @Override
            public void onNext(List<OrderCouponsListModel> listModels) {
                if (listModels != null && listModels.size() != 0) {
                    couponsList.clear();
                    couponsList.addAll(listModels);
                    imgRightCoupon.setVisibility(View.VISIBLE);
                    tvCoupon.setText("有" + listModels.size() + "个可用");
                } else {

                    tvCoupon.setText("无可用");

                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                Toast.makeText(PaidEndOfPaymentActivity2.this, "获取优惠券失败", Toast.LENGTH_SHORT).show();
            }
        }, this);
        orderCouponApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        orderCouponApi.setStoreId(storeId + "");
        orderCouponApi.setUserOrderId(userOrderId);
        HttpManager.getInstance().doHttpDeal(orderCouponApi);
    }

    private void userPayInfoData() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PREPAYBALANCEPAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
//        PhoneUtils.ShowToastMessage(this, storeId+"");
        params.addBodyParameter("orderNumber", orderNumber);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "支付尾款==" + result);
                String data = PhoneUtils.checkResponseFlag(PaidEndOfPaymentActivity2.this, result);
                try {
                    if (data != null) {
                        paymentData = new Gson().fromJson(data, PrePayBalancePaymentModel.class);

                        storeBalance = paymentData.getStoreBalance();//账户余额
                        tvAllJine = paymentData.getTotalPrice() + "";
                        tvEndOfPayment.setText("¥ " + String.format("%.2f", paymentData.getTotalPrice() - paymentData.getPayedDepositAmount()));//尾款金额
                        tvUseYue.setText("¥ " + String.format("%.2f", storeBalance));//账户余额
                        balanceMoney = Double.parseDouble(DecimalUtil.sub(paymentData.getTotalPrice() + "", paymentData.getPayedDepositAmount() + ""));
                        if (storeBalance < balanceMoney)
                            tvUseYueError.setVisibility(View.VISIBLE);
                        paymentData.setTailAmount(paymentData.getTotalPrice() - paymentData.getPayedDepositAmount());
                        Double companyId = JsonUtil.getJsonValuesDouble(data, "companyId");
                        Double companyCarId = JsonUtil.getJsonValuesDouble(data, "companyCarId");
                        if (companyCarId > 0 && companyId > 0) {
                            relatBill.setVisibility(View.VISIBLE);
                            isAllowBill = true;
                            etServiceDespostPrice.setShowMessage("挂账金额不能大于实际支付金额");
                            etServiceDespostPrice.setMaxMoney(balanceMoney);
                        }

                        relatSelectPayment.setVisibility(View.VISIBLE);
                        checkEndOfPayment();
//                        realityPaid =storeBalance- paymentData.getTailAmount();//实际支付
                        realityPaid = DecimalUtil.formatDoubleNum(balanceMoney - (storeBalance + couponMoney + billAmount));

                        tvActualPayment.setText("(实际支付¥" + DecimalUtil.formatNum(paymentData.getTailAmount() + "") + ")");
                        setPaymentNum();
                        if (storeBalance == 0) {
                            cbYue.setClickable(false);
                        } else {
                            cbYue.setClickable(true);
                        }

                        if (realityPaid >= 0) {
                            isUseStoreBalance = false;

                        } else {
                            isUseStoreBalance = true;
                        }

                    }
                } catch (Exception e) {
                    Log.e("King", "解析失败!");
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbYuEOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbYue.setChecked(true);
            return;
        }
        if (cbYue.isChecked()) {

            if (realityPaid <= 0) {  //当门店余额大于等于支付尾款时
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
                cbYue.setChecked(true);
                tvSdkPaidTip.setVisibility(View.GONE);
                tvUseYueError.setVisibility(View.GONE);
            } else {
                tvUseYueError.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setText("余额可支付¥" + String.format("%.2f", storeBalance) + ",还需第三方支付¥" + String.format("%.2f", Math.abs(realityPaid)));
            }
//            useStoreBalance = "true";
        } else {
            tvSdkPaidTip.setVisibility(View.GONE);

//            useStoreBalance = "false";
        }
    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }


        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(true);
            return;
        }

//        double dEndOfAmount = 0.00;
//        String sEndOfAmount = tvEndOfPayment.getText().toString().trim();
//        dEndOfAmount = Double.parseDouble(sEndOfAmount.substring(1, sEndOfAmount.length()));

        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            selectedPaidType = "aliPay";
            if (realityPaid <= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
                tvSdkPaidTip.setVisibility(View.GONE);

            }
        } else {
            selectedPaidType = "11";
        }


    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {
        if (!cbWeiXin.isChecked() && !cbZhiFuBao.isChecked() && !cbYue.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
        if (tvSdkPaidTip.getVisibility() == View.VISIBLE && !cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(true);
            return;
        }
//        double dEndOfAmount = 0.00;
//        String sEndOfAmount = tvEndOfPayment.getText().toString().trim();
//        dEndOfAmount = Double.parseDouble(sEndOfAmount.substring(1, sEndOfAmount.length()));

        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            selectedPaidType = "wxPay";
            if (realityPaid <= 0 && cbYue.isChecked() == true) {
                cbYue.setChecked(false);
                tvSdkPaidTip.setVisibility(View.GONE);
            }
        } else {
            selectedPaidType = "22";
        }


    }

    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSureOnClick(View view) {
        if (isAllBillAmount) {
            payEndOfPayMent();
        } else {
            if (cbYue.isChecked()) {
                if (!isUseStoreBalance && !cbZhiFuBao.isChecked() && !cbWeiXin.isChecked()) {
                    PhoneUtils.ShowToastMessage(this, "你还需要选择一种其他支付方式");
                    return;
                }
                myInputPwdUtil.show();
            } else {
                payEndOfPayMent();
            }
        }
    }


    private void payEndOfPayMent() {
        mLoadView.ShowLoadView();
        String couponsUserWalletid = "";
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PAYBALANCEPAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("orderNumber", orderNumber);
//        if (!isAllBillAmount) {

//            if (selectedPaidType.equals("aliPay") || selectedPaidType.equals("wxPay")) {
//                params.addBodyParameter("payType", selectedPaidType);
//            }
//        }
        if (cbZhiFuBao.isChecked() && !isAllBillAmount) {
            params.addBodyParameter("payType", "aliPay");

        } else if (cbWeiXin.isChecked() && !isAllBillAmount) {
            params.addBodyParameter("payType", "wxPay");
        }
        if (orderCouponsListModel != null) {
            params.addBodyParameter("couponsId", orderCouponsListModel.getCouponsId() + "");
            params.addBodyParameter("discountAmount", couponMoney + "");
        }

        params.addBodyParameter("useStoreBalance", isAllBillAmount ? String.valueOf(false) : cbYue.isChecked() + "");
        if (billAmount > 0) {
            params.addBodyParameter("hangAmount", billAmount + "");
        }
        MyLog.e("hep", params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(PaidEndOfPaymentActivity2.this, result);
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                if (!flag) {
                    return;
                }
                if (data.equals("")) {
                    updataUserInfo();
                } else {
                    if (cbZhiFuBao.isChecked()) {
                        aliPayPaid(data);
                    } else if (cbWeiXin.isChecked()) {
                        if (isWXAppInstalledAndSupported()) {
                            WXPayEntryActivity.wxPayPaidStart(PaidEndOfPaymentActivity2.this, data, "支付尾款成功");
                        } else {
                            PhoneUtils.ShowToastMessage(PaidEndOfPaymentActivity2.this, getString(R.string.isInstallwx));
                        }

                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaidEndOfPaymentActivity2.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //    跳转优惠券
    @OnClick(R.id.relative_discount_coupon)
    public void discountCouponOnClick(View view) {
        if (couponsList.size() == 0)
            return;
        Intent ti = new Intent(PaidEndOfPaymentActivity2.this, PicCouponActivity.class);
        ti.putExtra("couponList", (Serializable) couponsList);
        ti.putExtra("isPosition", isPosition);
        startActivityForResult(ti, COUPONS_LIST);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COUPONS_LIST && resultCode == RESULT_OK) {
            orderCouponsListModel = (OrderCouponsListModel) data.getSerializableExtra("couponsModel");
            isPosition = data.getIntExtra("isPosition", -1);
            if (isPosition == -1) {
                tvCoupon.setText("有" + couponsList.size() + "个可用");
                couponMoney = 0.00;
            } else {
                if (balanceMoney >= Double.parseDouble(orderCouponsListModel.getDiscountAmount())) {
                    tvCoupon.setText("-¥" + orderCouponsListModel.getDiscountAmount());
                    couponMoney = Double.parseDouble(orderCouponsListModel.getDiscountAmount());
                } else {
                    tvCoupon.setText("-¥" + balanceMoney);
                    couponMoney = balanceMoney;

                }
            }

            //当选取优惠券后，，重新计算最大挂账金额
            if (billAmount > (balanceMoney - couponMoney)) {
                etServiceDespostPrice.setText((balanceMoney - couponMoney) + "");
                billAmount = balanceMoney - couponMoney;
            }
            //当优惠劵足以支付尾款时候，隐藏挂账
            if ((balanceMoney - couponMoney) == 0) {
                relatBill.setVisibility(View.GONE);
            } else {
                if (relatBill.getVisibility() == View.GONE && isAllowBill) {
                    relatBill.setVisibility(View.VISIBLE);
                }

            }
            //设置变化后的最大挂账数
            etServiceDespostPrice.setMaxMoney(balanceMoney - couponMoney);

            realityPaid = DecimalUtil.formatDoubleNum(balanceMoney - (storeBalance + couponMoney + billAmount));
            //实际支付
            tvActualPayment.setText("(实际支付¥" + DecimalUtil.formatNum(balanceMoney - (couponMoney + billAmount) + "") + ")");
            setPaymentNum();
            if (realityPaid > 0) {
                isUseStoreBalance = false;
                //是否显示余额不足
                tvUseYueError.setVisibility(View.VISIBLE);
                tvSdkPaidTip.setVisibility(View.VISIBLE);
            } else {
                isUseStoreBalance = true;
                tvUseYueError.setVisibility(View.GONE);
                tvSdkPaidTip.setVisibility(View.GONE);
            }
            //当不需要三方支付和余额支付时
            if (balanceMoney - couponMoney - billAmount > 0) {
                isAllBillAmount = false;
                relatBalance.setVisibility(View.VISIBLE);
                linearThreePayment.setVisibility(View.VISIBLE);
            } else {
                isAllBillAmount = true;
                relatBalance.setVisibility(View.GONE);
                linearThreePayment.setVisibility(View.GONE);
            }

            if (cbYue.isChecked()) {
                if (realityPaid > 0) {
                    tvSdkPaidTip.setVisibility(View.VISIBLE);
                    tvUseYueError.setVisibility(View.VISIBLE);


                } else {
                    if (cbYue.isChecked()) {
                        cbZhiFuBao.setChecked(false);
                        cbWeiXin.setChecked(false);
                    }
                    tvSdkPaidTip.setVisibility(View.GONE);
                    tvUseYueError.setVisibility(View.GONE);
                }
                if (tvSdkPaidTip.getVisibility() == View.VISIBLE) {
                    tvSdkPaidTip.setText("余额可支付¥" + String.format("%.2f", storeBalance) + ",还需第三方支付¥" + String.format("%.2f", Math.abs(realityPaid)));
                }
            } else {
                tvSdkPaidTip.setVisibility(View.GONE);
                if (realityPaid > 0) {
                    tvUseYueError.setVisibility(View.VISIBLE);

                } else {
                    tvUseYueError.setVisibility(View.GONE);

                }
            }


        }

    }

    //最后显示尾款
    private void showEndOnPayment() {
        MyLog.e("yang", "尾款==" + paymentData.getTailAmount());
        double dEndOfAmount = paymentData.getTotalPrice() - paymentData.getPayedDepositAmount();//尾款金额
        double dCardAmount = 0.00;
        double dCouponAmount = 0.00;
        if (tvProjectCard.getText().toString().contains("￥")) {
            String sCardAmount = tvProjectCard.getText().toString().trim();
            dCardAmount = Double.parseDouble(sCardAmount.substring(2, sCardAmount.length()));
        }

        if (tvCoupon.getText().toString().contains("￥")) {
            String sCouponAmount = tvCoupon.getText().toString().trim();
            dCouponAmount = Double.parseDouble(sCouponAmount.substring(2, sCouponAmount.length()));
        }

        if (dEndOfAmount <= dCardAmount + dCouponAmount) {
            tvEndOfPayment.setText("￥0.00");
        } else {
            tvEndOfPayment.setText("￥" + String.format("%.2f", dEndOfAmount - dCardAmount - dCouponAmount));//尾款金额
        }
        checkEndOfPayment();
    }


    private void updataUserInfo() {
        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
        if (!isMessage) {
            Intent intent = new Intent();
            intent.setAction(SubscribeOrdelActivity.orderAction);
//        if (SubscribeOrdelActivity.currentId() == 0) {
//            intent.putExtra("currentId", 0);
//        } else if (SubscribeOrdelActivity.currentId() == 1) {
            intent.putExtra("currentId", 4);
//        }
            sendBroadcast(intent);
        } else {
            startActivity(new Intent(PaidEndOfPaymentActivity2.this, SubscribeOrdelActivity2.class).putExtra("currentId", 4));

        }
        RxBus.getDefault().post(new CommonEvent("详情尾款支付成功"));
        PhoneUtils.ShowToastMessage(this, "支付成功");
        finish();
//        getOrderSuccess();
    }

    public void getPaymentCancle() {
        PaymentCancleApi paymentCancleApi = new PaymentCancleApi(new HttpOnNextListener() {
            @Override
            public void onNext(Object o) {

            }
        }, this);
        paymentCancleApi.setSession(UserHelper.getInstance().getSession(this));
        paymentCancleApi.setUserOrderId(userOrderId);
        paymentCancleApi.setStoreId(storeId + "");

        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(paymentCancleApi);
    }

    @Subscribe(code = Constants.PAID_SUCCESS_ENDOF_PAYMENT, threadMode = ThreadMode.MAIN)
    public void eventPaidSuccess(CommonEvent paidSuccessEvent) {
        if ("cancle".equals(StringUtils.getString(paidSuccessEvent.getType()))) {
            getPaymentCancle();
        } else if ("error".equals(StringUtils.getString(paidSuccessEvent.getType()))) {
            getPaymentCancle();
        } else {
            updataUserInfo();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }


    private void checkEndOfPayment() {
        if (tvEndOfPayment.getText().toString().equals("￥0.00")) {
            cbYue.setChecked(false);
            cbYue.setClickable(false);
            cbZhiFuBao.setChecked(false);
            cbZhiFuBao.setClickable(false);
            cbWeiXin.setChecked(false);
            cbWeiXin.setClickable(false);
        } else {
            cbYue.setChecked(false);
            cbYue.setClickable(true);
            cbZhiFuBao.setChecked(true);
            cbZhiFuBao.setClickable(true);
            cbWeiXin.setChecked(false);
            cbWeiXin.setClickable(true);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
